package com.ejlchina.tool.fragment

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.navigation.fragment.findNavController
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.FragmentStartupBinding
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.network.NetApi
import com.ejlchina.tool.util.DeviceUtil
import com.ejlchina.tool.util.bytearray.reversalEvery2Charts
import com.ejlchina.tool.util.deleteFile
import com.ejlchina.tool.util.showToast

class StartupFragment : BaseBindingFragment2<FragmentStartupBinding>() {

    //启用蓝牙
    private val enableBluetooth = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                showToast("蓝牙已打开")
//                findNavController().navigate(R.id.action_startup_to_scan_fragment)
            } else {
                showToast("蓝牙关闭")
            }
        }

    //蓝牙连接权限
    private val enableBluetoothConnect = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
        val resultScan = result[Manifest.permission.BLUETOOTH_SCAN]
        val resultConnect = result[Manifest.permission.BLUETOOTH_CONNECT]
        val resultAdvertise = result[Manifest.permission.BLUETOOTH_ADVERTISE]
        if (resultScan == true && resultConnect == true && resultAdvertise == true) {
            enableBluetooth.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))
        } else {
            showToast("连接权限被拒绝")
        }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setHeadVisibility(View.GONE)
        binding.btnOpenBluetooth.setOnClickListener {
            checkBluetoothConnectPermission()
        }
    }

    private fun checkBluetoothConnectPermission() {
        if (isAndroid12()) {
            enableBluetoothConnect.launch(arrayOf(
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_ADVERTISE
                )
            )
        }else {
            enableBluetooth.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))
        }
    }

    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentStartupBinding {
        return FragmentStartupBinding.inflate(inflater, container, true)
    }

}